function ParseRank(json)
{	
	return {
			name: json.fields.dish.name,
			place: json.fields.dish.place_name,
			id: json.fields.dish.id,
            reviewText: json.fields.comment,
			done: false,
	};
}

$(function(){

  window.DishRankItem = Backbone.Model.extend({
    ERROR: "this dish has no name...something went wrong.",

    initialize: function() {
      if (!this.get("name")) {
        this.set({"name": this.ERROR});
      }
    },

    clear: function() {
	  this.destroy(); // issues DELETE request to /api/ranks/t/[rankId]/[dishId]
	  this.collection.remove(this);
      this.view.remove();
    }

  });

  window.Ranking = Backbone.Collection.extend({
    model: DishRankItem,

    done: function() {
      return this.filter(function(todo){ return todo.get('done'); });
    },

    remaining: function() {
      return this.without.apply(this, this.done());
    },
	
	parse: function(response) {
		if (response == null) return;
		var ranks = _.map(response, ParseRank);
		return ranks;
	},

  });

  window.Ranks = new Ranking;

  window.MyRankView = Backbone.View.extend({
    tagName:  "li",
    template: _.template($('#my-rank-item-template').html()),

    events: {
      //"click .check"              : "toggleDone",
      "dblclick span.dish-name"		: "edit",
      "click span.delete"			: "clear",
      "keypress .review-textarea"	: "updateOnEnter",
	  "click .review-textarea"		: "clearText"
    },

    initialize: function() {
      _.bindAll(this, 'render', 'close');
      this.model.bind('change', this.render);
      this.model.view = this;
    },

    render: function() {
      $(this.el).html(this.template(this.model.toJSON()));
	  this.setName();
      return this;
    },
	
	setName: function() {
		var name = this.model.get('name');
		this.$('.dish-name').text(name);
		var reviewText = this.model.get('reviewText');
		this.$('.review-content').text(reviewText);
		this.input = this.$('.review-textarea');
		this.input.bind('blur', this.close);
		
		if (reviewText) {
			this.input.val(reviewText);
		}
		else {
			this.input.val("Any comments on the " + name + "?");
		}
    },
	
    edit: function() {
      $(this.el).addClass("editing");
      this.input.focus();
    },

    close: function() {
	  this.model.set({"reviewText": this.input.val()});
      //this.model.save({content: this.input.val()});
      $(this.el).removeClass("editing");
    },

    updateOnEnter: function(e) {
      if (e.keyCode == 13) this.close();
    },
	
	clearText: function() {
		var name = this.model.get('name');
		if (this.input.val() == "Any comments on the " + name + "?") {
			this.input.val('');
		}
	},

    remove: function() {
      $(this.el).fadeOut();
	  $(this.el).remove();
	  
	  // if there is nothing in ranking, reset state to beginning
	  
	  
	  
    },

    clear: function() {
      this.model.clear();
    }

  });

  window.AppView = Backbone.View.extend({
    el: $("#rank-app"),

    statsTemplate: _.template($('#stats-template').html()),

    events: {
      //"keypress #new-rank":  "createOnEnter",
      //"keyup #new-rank":     "showTooltip",
      //"click .todo-clear a": "clearCompleted",
	  "click .inline-heading-button": "submit",
    },

    initialize: function() {
		_.bindAll(this, 'addOne', 'addAll', 'render');

		//this.input = this.$("#new-rank");
		Ranks.bind('add',     this.addOne);
		Ranks.bind('refresh', this.addAll);
		Ranks.bind('all',     this.render);
	  
		var tagId = $("#tag-id").text();
		if (tagId == "") return;
		Ranks.url = "/api/ranks/t/" + tagId;
		Ranks.fetch();
	},

    render: function() {
      	 
	  var done = Ranks.done().length;
      this.$('#ranking-stats').html(this.statsTemplate({
        total:      Ranks.length,
        done:       Ranks.done().length,
        remaining:  Ranks.remaining().length
      }));
    },

    addOne: function(rank) {
		
		// if first one added
		if (this.$(".placeholder").is(":visible")) {
		
			this.$(".placeholder").fadeOut(400, function() {
				var view = new MyRankView({model: rank});
				$("#my-ranking-list").append(view.render().el);
				$("#instructions").fadeIn();
				$("#ranking-stats").fadeIn();
				$(".inline-heading-button").fadeIn();
			});
		}
		else {
			var view = new MyRankView({model: rank});
			this.$("#my-ranking-list").append(view.render().el);
		}
		
    },
	
    addAll: function() {
      Ranks.each(this.addOne);
    },

    // newAttributes: function() {
      // return {
        // name: this.input.val(),
        // rating:    false,
      // };
    // },

    // createOnEnter: function(e) {
      // if (e.keyCode != 13) return;
	  // Ranks.add(new DishRankItem(this.newAttributes()));
      // //Ranks.create(this.newAttributes());
      // this.input.val('');
    // },

	
    createFromRankItem: function(args) {
		var alreadyAdded = Ranks.any(function(rank) {
			return rank.id == args.id;
		});
		
		if (alreadyAdded) {
			// display some indicator to user
			return;
		}
		
		var dishRankItem = new DishRankItem({ 
			name: args.name, 
			done: false, 
			id: args.id, 
			place: args.place,
			reviewText: args.reviewText,
		});
		
		dishRankItem.collection = Ranks;
		Ranks.add(dishRankItem);
		//Ranks.create(this.newAttributes());
    },
	
    // clearCompleted: function() {
      // _.each(Ranks.done(), function(rank){ rank.clear(); });
      // return false;
    // },
	
	submit: function() {
		order = [];
		$(".my-rank-item").each(function (idx, elm) {
			order.push(elm.id);
		});
		
		
		reviews = [];
		$(".review-content").each(function (idx, elm) {
			reviews.push(elm.textContent);
		});
		
		var tagId = $("#tag-id").text();
		$.post("/submit/ranking/", JSON.stringify({ 
			ranking: order, 
			text: reviews, 
			tagId: tagId
		}), function(data) {
				if (data != 'Success' || data != 'Fail') {
					// user must login
					
				}
                //$(".inline-heading-button").text(data);
        });
	},
	
    showTooltip: function(e) {
      var tooltip = this.$(".ui-tooltip-top");
      var val = this.input.val();
      tooltip.fadeOut();
      if (this.tooltipTimeout) clearTimeout(this.tooltipTimeout);
      if (val == '' || val == this.input.attr('placeholder')) return;
      var show = function(){ tooltip.show().fadeIn(); };
      this.tooltipTimeout = _.delay(show, 1000);
    }

  });

  window.RankApp = new AppView;

});
